package org.artifact.core.lang;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.artifact.core.enums.ServerStatusEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import lombok.Getter;
import lombok.Setter;

public class IServer {
	static final Logger log = LoggerFactory.getLogger(IServer.class);
	@Getter
	private final IContext context = new IContext();
	@Getter
	private final Plugins plugins = new Plugins();
	@Getter
	@Setter
	private IConfig config;
	
	@Getter
	public ServerStatusEnum status = ServerStatusEnum.STOP;
	
	// 属性
	private Map<String, Object> attr = new ConcurrentHashMap<>();
	
	private static final IServer ME = new IServer();

	private IServer() {
	}

	public static IServer me() {
		return ME;
	}

	/**
	 * 取得属性
	 * 
	 * @param key
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public <T> T getAttr(String key){
		return (T) attr.get(key);
	}

	/**
	 * 设置属性
	 * 
	 * @param key
	 * @param value
	 */
	public void setAttr(String key, Object value){
		attr.put(key, value);
	}

	/**
	 * 删除属性
	 * 
	 * @param key
	 */
	public void removeAttr(String key){
		attr.remove(key);
	}
	
	/**
	 * 清空属性
	 */
	public void clearAttr(){
		attr.clear();
	}
	
	public ServerStatusEnum start() {
		if (config == null) {
			throw new RuntimeException("config can not be null");
		}
		if (status != ServerStatusEnum.STOP) {
			throw new RuntimeException("Incorrect state");
		}
		status = ServerStatusEnum.STARTING;
		log.info("-> Server Starting");
		// 初始化
		config.configContext(context);
		// 添加插件
		config.configPlugin(plugins);
		// 启动插件
		plugins.start();
		// 启动完毕后调用
		config.afterServerStart();

		status = ServerStatusEnum.RUNNING;
		log.info("-> Server Start Finish");
		return status;
	}

	public ServerStatusEnum stop() {
		status = ServerStatusEnum.STOPPING;
		log.info("-> Server Stoping");

		log.info("-> Stop Plugins");
		// 停止前调用
		config.beforeServerStop();
		// 停止插件
		plugins.stop();
		// 修改服务器状态
		status = ServerStatusEnum.STOP;
		log.info("-> Server Stop Finish");

		return status;
	}

}